<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {
//	public $data = array();
	public $startDate='';
	public $endDate='';
	public function __construct()
	{
		parent::__construct();
		header('Content-Type: application/json');
		$this->load->model('api_model','a');
		$this->check_apikey();
        $system = $this->a->get_by_system();
        $this->startDate = $system['sys_start_time'];
        $this->endDate = $system['sys_over_time'];
	}
	
	//调用小程序接口，code换取openid
	public function get_token()
	{
		$code = $this->input->get("code");
		
		$url="https://api.weixin.qq.com/sns/jscode2session?appid=".APPID."&secret=".APPSEC."&js_code=".$code."&grant_type=authorization_code";
		
		$result = json_decode(file_get_contents($url),true);
		
		if(!array_key_exists("openid",$result))
		{
			$response = array(
				'code' => 100,
				'message' => 'code无效'
			);



        }else{
            $token = uniqid();
            $openid = $result["openid"];
            $this->load->model("tokens_model");
            $this->tokens_model->insert(array("tok_key"=>$token,"tok_openid"=>$openid));

            $this->load->model("users_model");
            $user = $this->users_model->get_by_id($openid);
            if(empty($user)){
                $this->users_model->insert(array("openid"=>$openid));
            }

            $response = array(
                'code' => 0,
                'message' => '登陆成功',
                'token'=>$token

            );
        }

		echo json_encode($response);
	}
	
	private function get_openid($tok_key)
	{
		$this->load->model("tokens_model");
		$token = $this->tokens_model->get_by_key($tok_key);
		return $token["tok_openid"];
	}

	private function check_apikey()
	{
		 //检查APIKEY
		$apikey = $this->input->get_request_header("APIKEY");

		if($apikey!=APIKEY)
		{
			$response = array(
				'code' => 100,
				'message' => 'apikey 错误'
			);

			echo json_encode($response);
			exit(0);
		}
	}
	
	public function update_userinfo()
	{
		$userinfo = array(
			"nickName" => $this->input->get("nickName"),
			"gender" => $this->input->get("gender"),
			"city" => $this->input->get("city"),
			"province" => $this->input->get("province"),
			"country" => $this->input->get("country"),
			"avatarUrl" => $this->input->get("avatarUrl")
		);
		
		$token = $this->input->get("token");
		$openid = $this->get_openid($token);
		
		$this->load->model("users_model");
		$this->users_model->update($openid,$userinfo);
		
		$response = array(
			'code' => 0,
			'message' => 'success'
		);
		echo json_encode($response);
	}
	
	//用于测试小程序接口调用
	public function test()
	{
		$response = array(
			'code' => 0,
			'message' => '接口调用测试成功'
		);
		echo json_encode($response);
	}

	## ---------------------------
    //参与打卡
    public function particiCallenge(){
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);

        $tomorrowuser = $this->a->get_callenge_user_status(1,$openid);
        if($tomorrowuser){
            $data['utomorrow'] = 1;
        }else{
            $data['utomorrow'] = 0;
        }
        $todayuser = $this->a->get_callenge_user_status(0,$openid);
        if($todayuser){
            $data['utoday'] = 1;
            if(1==$todayuser['sr_is_close']){
                $data['utoday_is_close'] = 1;
            }else{
                $data['utoday_is_close'] = 0;
            }
            if(1==$todayuser['sr_status']){
                $data['utoday_status'] = 1;
            }else{
                $data['utoday_status'] = 0;
            }
        }else{
            $data['utoday'] = 0;
            $data['utoday_is_close'] = 0;
        }
        $tomorrowcallenge = $this->a->get_the_callenge(1);
        $tomorrowcallenge['user'] = $this->a->partici_tomorrow_user($tomorrowcallenge['call_id']);
        $todaycallenge = $this->a->get_the_callenge(0);
        $todaycallenge['user']['userMoney'] = $this->a->get_user_champion($todaycallenge['call_id'],1);
        $todaycallenge['user']['userDate'] = $this->a->get_user_champion($todaycallenge['call_id'],2);
        $todaycallenge['user']['userNum'] = $this->a->get_user_champion($todaycallenge['call_id'],3);
        $output = array(
            'code' => '200',
            'message' => 'ok',
            'data' => array(
            'tomorrowcallenge'=>$tomorrowcallenge,
            'todaycallenge'=>$todaycallenge,
                'nowtime' => date('Y-m-d H:i:s',time()),
                'user' =>$data,
                'particiDate' => array(
                    'startDate' =>$this->startDate,
                    'endDate' => $this->endDate
                )

            )
        );

        echo json_encode($output);
    }

    //the day callenge info
    public function callengeInfo(){
	    $callenge = $this->a->get_the_callenge();
	    $callenge['start_time'] = $this->startDate;
	    $callenge['over_time'] = $this->endDate;
	    $output = array(
	        'code' => '200',
            'message' => 'ok',
            'data' => $callenge
        );
	    echo json_encode($output);exit;
    }
    // user record
    public function userInfo(){
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);
        $user = $this->a->get_by_user($openid);
        $sign = $this->a->get_all_sign($openid);
        foreach($sign as &$v){
            $v['sr_money'] = $v['sr_pay'];
            if(1==$v['sr_status']){
                $v['sr_money'] = $v['sr_acquire_money'];
            }
        }

        $output = array(
            'code' => 200,
            'message' => 'ok',
            'data' => array(
                'user'=>$user,
                'sign'=>$sign
            )
        );
        echo json_encode($output);exit;
    }

    public function execSign(){
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);
        $id = $this->input->get('call_id');
        $sr_formid = $this->input->get('sr_formid');
        if(time()<strtotime($this->startDate)){
            //你来早可打卡时间未到
            $output = array(
                'code' => 501,
                'message' => '您来早了，打卡时间未到'
            );
            echo json_encode($output);exit;
        }
        if(time()>strtotime($this->endDate)){
            //打卡时间已过
            $output = array(
                'code' => 501,
                'message' => '打卡时间已过'
            );
            echo json_encode($output);exit;
        }

        $this->a->user_succeed_sign($openid,$id,$sr_formid);
        $output = array(
            'code' => 200,
            'message' => 'ok'
        );
        echo json_encode($output);exit;
    }

    /**
     * 参加打卡
     */
    public function participationCall(){
        $token = $this->input->get("token");
        $data['sr_formid'] = $this->input->get('sr_formid');
        $openid = $this->get_openid($token);
        $id = $this->input->get('call_id');
        $data['sr_callenge'] = $id;
        $data['sr_user'] = $openid;
        $data['sr_pay'] = 1;
        $data['sr_pay_time'] = time();
        $data['sr_time'] = date("Y-m-d",strtotime('1 day'));
        $data['sr_is_close'] = 0;
        $query = $this->a->create_sign_record($data);
        $this->a->sign_update_call_status($id,$openid);
        if($query){
            $output = array(
                'code' => 200,
                'message' => 'ok'
            );
        }else{
            $output = array(
                'code' => 501,
                'message' => '参与失败'
            );
        }
        echo json_encode($output);exit;
    }

    //wx pay param
    public function wxPay(){
        require_once APPPATH."third_party/Wxpay/lib/WxPayApi.php";
        require_once APPPATH."third_party/Wxpay/lib/WxPay.Notify.php";
        $token = $this->input->get("token");
        $data['sr_formid'] = $this->input->get('sr_formid');
        $data['call_id'] = $this->input->get('call_id');
        if(!$data['call_id']){
            $output = array(
                'code' => 20001,
                'message' => 'call_id不存在！'
            );
            echo json_encode($output);die;
        }

        if(!$data['sr_formid']){
            $output = array(
                'code' => 20001,
                'message' => 'sr_formid不存在！'
            );
            echo json_encode($output);die;
        }
//        var_dump($data);die;
        $openid = $this->get_openid($token);
        //统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody("早期打卡挑战");  //设置商品或支付单简要描述
        $input->SetOut_trade_no('cz'.mt_rand(100000,999999).time()); //设置商户系统内部的订单号,32个字符内、可包含字母, 其他说明见商户订单号
        $input->SetTotal_fee("100"); //设置订单总金额，只能为整数，详见支付金额
        $input->SetNotify_url(site_url('pages/notify')); //设置接收微信支付异步通知回调地址
        $input->SetTrade_type("JSAPI"); //设置取值如下：JSAPI，NATIVE，APP，详细说明见参数规定
        $input->SetOpenid($openid);
        $input->SetAttach(json_encode($data));
        $order = WxPayApi::unifiedOrder($input);

        $parameters = $this->getJsApiParameters($order);

        $output = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $parameters,
            'sss'=>$data
        );
        echo json_encode($output);
    }

    private function getJsApiParameters($UnifiedOrderResult)
    {    //判断是否统一下单返回了prepay_id
        if(!array_key_exists("appid", $UnifiedOrderResult)
            || !array_key_exists("prepay_id", $UnifiedOrderResult)
            || $UnifiedOrderResult['prepay_id'] == "")
        {
            throw new WxPayException("参数错误");
        }
        $jsapi = new WxPayJsApiPay();
        $jsapi->SetAppid($UnifiedOrderResult["appid"]);
        $timeStamp = time();
        $jsapi->SetTimeStamp("$timeStamp");
        $jsapi->SetNonceStr(WxPayApi::getNonceStr());
        $jsapi->SetPackage("prepay_id=" . $UnifiedOrderResult['prepay_id']);
        $jsapi->SetSignType("MD5");
        $jsapi->SetPaySign($jsapi->MakeSign());
        $parameters = $jsapi->GetValues();
        return $parameters;
    }


//海报
    public function poster(){
        require_once APPPATH.'third_party/utils.php';
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);
        $user = $this->a->get_by_user($openid);
        $procode_img = 'uploads/'.APPID.'.png';
        $procode_url = 'uploads/'.$openid.date('YmdHis').'.jpg';
        if(!is_file($procode_img)){
        $this->load->library('wxapplet');
        $access_token = $this->wxapplet->get_access_token();
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=".$access_token;
        $data = array(
            'path'=>'pages/index',
            'width'=>430
        );
        $procedure_code = $this->wxapplet->http_post($url,json_encode($data));
        file_put_contents($procode_img,$procedure_code);
        }
        $target = imagecreatefromjpeg("uploads/template/daka_1.jpg");
        mergeImage($target, $procode_img, array('left' => 400, 'top' => 600, 'width' => 400, 'height' => 400));
        mergeImage($target, $user['avatarUrl'], array('left' => 400, 'top' => 100, 'width' => 200, 'height' => 220));
        imagejpeg($target,$procode_url);
        $output = array(
            'code' => 200,
            'message' => 'ok',
            'date' =>base_url($procode_url)
        );
        echo json_encode($output);
    }
//打卡失败状态
    public function signStatusNo(){
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);
        $call = $this->input->get("call_id");
        $this->a->sign_status_no($call,$openid);
    }
//生成反馈意见
    public function addFeedback(){
        $token = $this->input->get("token");
        $openid = $this->get_openid($token);
        $data['fd_openid'] = $openid;
        $data['fd_content'] = trim(strip_tags($this->input->get('content')));
        $data['fd_contact'] = $this->input->get('phone');
        $data['fd_time'] = time();
        $query = $this->a->insert_feedback($data);
        $output = array(
            'code' => 200,
            'message' => 'ok',
        );
        echo json_encode($output);
    }

    /**
     * 用户提现
     */
    public function withdraw_money(){
        $token = $this->input->post("token");
        $openid = $this->get_openid($token);
        $user = $this->a->get_by_user($openid);
        $money = $this->input->post('money');
        if(!$user){
            $output = array(
                'code' => 20003,
                'message' => '当前用户不存在！',
            );
            echo json_encode($output);die;
        }
        if($money > $user['money']){
            $output = array(
                'code' => 20003,
                'message' => '您的余额不足！',
            );
            echo json_encode($output);die;
        }
        if($money < 1){
            $output = array(
                'code' => 20003,
                'message' => '提现金额不能小于1元',
            );
            echo json_encode($output);die;
        }
        $url = 'http://www.xiaozaixiao.com/weixinpush/pushredpack?authid=Q2w0U1h4UkZDdCsrazFRek1ubmdXdz09&appid=wxb7b39afe94434787';
        $data = [
        'Name'=>'天天早起赢奖金',//红包名称
         'AppId'=>'wxb7b39afe94434787', //公众号id
         'NickName'=>$user['nickName'],//用户昵称
         'TransId'=>'tz'.time().rand(1000, 9999),'',//交易编号，可为空
         'Title'=>'再接再厉',//红包祝福语
         'Remark'=>'用户提现',// 红包备注，内部自己看
         'PriceVal' => 1,//单位元，1-200之间
         'SendType'=>'零钱',//红包/零钱
         'OpenId'=>$openid,//用户的openid
         'SendConfigId'=>'464a7d15-642f-49a9-82a8-5a3df8f698c3',//实际下发红包的发送的配置选项，如果没有就填写
             //464a7d15-642f-49a9-82a8-5a3df8f698c3
         'FromAppName'=>'早起赢奖金提现'//用户收到的红包抬头
         ];
        $da = [
            'wd_openid'=>$openid,
            'wd_money'=>$money,
            'wd_time'=>time(),
            'wd_status'=>0,
            'wd_no'=>$data['TransId']
        ];
        $this->a->insert_wd($da);
        $param = $this->ToUrlParams($data);
        $query = $this->http_post($url,$param);
        if(json_decode($query,true)['Code']==200 || json_decode($query,true)['Code']==302){
            for($i = 0; $i<3;$i++){
                $userMoney = $this->a->update_user_money($openid,$money);
                if($userMoney){
                    break;
                }
            }

            for($i = 0; $i<3;$i++){
                $userWd = $this->a->update_wd($data['TransId']);
                if($userWd){
                    break;
                }
            }
            $this->a->update_wd($data['TransId']);
        }
        echo $query;die;
    }

    //json only
    private function http_post($url,$data){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        //$header = array("Content-Type: application/json; encoding=utf-8");
        curl_setopt($oCurl, CURLOPT_URL, $url);//设置链接
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
        curl_setopt($oCurl, CURLOPT_POST, 1);//设置为POST方式
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $data);//POST数据
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * 格式化参数格式化成url参数
     */
    private function ToUrlParams($Parameters)
    {
        $buff = "";
        foreach ($Parameters as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

}
